package com.pll.client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import jakarta.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Component
@ClientEndpoint
public class ChatClient {

    private static final Logger log = LoggerFactory.getLogger(ChatClient.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    private Session session;
    private final String serverUri = "ws://localhost:8023/ws/chat/merchant/"; // manage 模块的地址和端口

    private Long currentMerchantId;

    public void connect(Long merchantId) {
        if (merchantId == null) {
            log.error("无法连接WebSocket，商家ID为空。");
            return;
        }
        this.currentMerchantId = merchantId;
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            URI uri = new URI(serverUri + this.currentMerchantId);
            this.session = container.connectToServer(this, uri);
        } catch (Exception e) {
            log.error("连接到WebSocket服务器失败: {}", e.getMessage());
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        log.info("商家端连接成功: {}", session.getId());
    }

    @OnMessage
    public void onMessage(String message) {
        // 这里处理从用户收到的消息
        log.info("收到来自用户的消息: {}", message);
        // 在这里，您可以将消息推送到商家的后台管理界面
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        this.session = null;
        log.info("商家端连接关闭: {}, 原因: {}", session.getId(), reason);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("商家端WebSocket发生错误", error);
    }

    /**
     * 发送消息给用户
     * @param userId 目标用户的ID
     * @param content 消息内容
     */
    public void sendMessageToUser(Long userId, String content) {
        if (this.session == null || !this.session.isOpen()) {
            log.warn("WebSocket连接未建立或已关闭，无法发送消息。");
            return;
        }

        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("toType", "user");
            payload.put("toId", userId);
            payload.put("content", content);

            String message = objectMapper.writeValueAsString(payload);
            this.session.getBasicRemote().sendText(message);
            log.info("向用户 {} 发送消息: {}", userId, content);
        } catch (JsonProcessingException e) {
            log.error("构建消息JSON失败", e);
        } catch (IOException e) {
            log.error("发送消息失败", e);
        }
    }
} 